package com.example.zx.theline.lyjh.pub;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zx.theline.R;
import com.example.zx.theline.pub.CheckInfoActivity;
import com.scu.miomin.shswiperefresh.view.SHListView;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;

import GsonBean.SgqdBean;
import GsonBean.SuccessBean;
import GsonBean.post.MySgbOpeartion;
import GsonBean.post.SgbDhzPost;
import GsonBean.post.SgbThPost;
import GsonBean.post.SgbhzPost;
import Utils.DeviceUuidFactory;
import Utils.MyToast;
import Utils.PopUtils;
import Utils.RefreshManager;
import app.MyApplication;
import base.BaseActivity;
import dialog.CenterDialog;
import dialog.CustomDialog;
import dialog.ThDialog;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 计划审核 施工办审核
 */
@SuppressWarnings("unused")
public class JhshSgbshActivity extends BaseActivity implements View.OnClickListener {

    public static GsonBean.ShyjhxqBean ZsyjhxxShBean;
    //标题
    private TextView centerTextView;
    //计划内容
    private TextView lb, yf, ydbh, kssj, xm, dd, hb, lc, xmmc, sgnr, sgjx, blfh;
    // 相关单位
    private TextView sgdw, sgdwfzr, jldw, jldwfzr, jsdw, cwzd, sbgldw, qtdw, shcs, xmzgbm;
    // 按钮
    private TextView tv_chakan, tv_shliucheng, tv_cancel, tv_hz, tv_dhz, tv_th, tv_qhqd, tv_szlc;
    private TextView rightTextView, leftTextView;
    private Intent intent;

    private CenterDialog mCenterDialog;
    private ThDialog mThDialog;

    //施工办汇总Post Bean
    private SgbhzPost mSgbhzPost;
    private SgbDhzPost mSgbDhzPost;
    private SgbThPost mSgbThPost;

    //施工办切换区段
    private PopupWindow popupWindow;
    private SHListView popListView;
    private TextView popConfirm, selectQdName, currentSgqd;
    private EditText popEdit; //PopupWindow中的输入框
    private LayoutInflater inflater;
    private View view;
    private CustomDialog customDialog;
    private TextView dialogCancel, dialogConfirm;
    private SelectAdapter mSelectAdapter;
    //Data
    private List<SgqdBean.SgqdListBean> mChangeList = new ArrayList<>();
    private SgqdBean sgqdBean;
    private LinearLayout blfh_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jhsh_sgbsh);
        InitView();
        InitData();
        InitListen();
    }

    @Override
    protected void InitView() {

        centerTextView = (TextView) findViewById(R.id.centerTextView);
        centerTextView.setText("月计划详情");

        lb = (TextView) findViewById(R.id.lb);
        yf = (TextView) findViewById(R.id.yf);
        ydbh = (TextView) findViewById(R.id.ydbh);
        kssj = (TextView) findViewById(R.id.kssj);
        xm = (TextView) findViewById(R.id.xm);
        dd = (TextView) findViewById(R.id.dd);
        hb = (TextView) findViewById(R.id.hb);
        lc = (TextView) findViewById(R.id.lc);
        xmmc = (TextView) findViewById(R.id.xmmc);
        sgnr = (TextView) findViewById(R.id.sgnr);
        sgjx = (TextView) findViewById(R.id.sgjx);
        blfh = (TextView) findViewById(R.id.blfh);
        blfh_layout = (LinearLayout) findViewById(R.id.blfh_layout);

        sgdw = (TextView) findViewById(R.id.sgdw);
        sgdwfzr = (TextView) findViewById(R.id.sgdwfzr);
        jldw = (TextView) findViewById(R.id.jldw);
        jldwfzr = (TextView) findViewById(R.id.jldwfzr);
        jsdw = (TextView) findViewById(R.id.jsdw);
        cwzd = (TextView) findViewById(R.id.cwzd);
        sbgldw = (TextView) findViewById(R.id.sbgldw);
        qtdw = (TextView) findViewById(R.id.qtdw);
        shcs = (TextView) findViewById(R.id.shcs);
        xmzgbm = (TextView) findViewById(R.id.xmzgbm);
        currentSgqd = (TextView) findViewById(R.id.current_sgqd);

        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        tv_chakan = (TextView) findViewById(R.id.tv_chakan);
        tv_shliucheng = (TextView) findViewById(R.id.tv_shliucheng);
        tv_hz = (TextView) findViewById(R.id.tv_hz);
//        tv_dhz = (TextView) findViewById(R.id.tv_dhz);
        tv_th = (TextView) findViewById(R.id.tv_th);
        tv_qhqd = (TextView) findViewById(R.id.tv_qhqd);
        tv_szlc = (TextView) findViewById(R.id.tv_szlc);

        leftTextView = (TextView) findViewById(R.id.leftTextView);
        rightTextView = (TextView) findViewById(R.id.rightTextView);
        customDialog = new CustomDialog(this, R.layout.dialog_confirm_tips, R.style.Theme_dialog);
        dialogCancel = (TextView) customDialog.findViewById(R.id.btn_dialog_cancel);
        dialogConfirm = (TextView) customDialog.findViewById(R.id.btn_dialog_confirm);
        customDialog.setCanceledOnTouchOutside(false);
    }

    @Override
    protected void InitData() {
        rightTextView.setVisibility(View.GONE);
        requestSgqdList(); //请求施工办数据列表

        if (ZsyjhxxShBean == null) {
            MyApplication.ShowWaitDialog(this);
            MyApplication.setWaitDialogMsg("数据错误");
        } else {
            lb.setText(ZsyjhxxShBean.getInfo().getLb());
            yf.setText(ZsyjhxxShBean.getInfo().getSgny());
            ydbh.setText(ZsyjhxxShBean.getInfo().getBh());
            //后台数据缺少日期时间
//            rqsj.setText(ZsyjhxxBean.getInfo().getSgrq());
            kssj.setText(ZsyjhxxShBean.getInfo().getExsgrq());
            xm.setText(ZsyjhxxShBean.getInfo().getXlxbList().get(0).getXlmc());
            dd.setText(ZsyjhxxShBean.getInfo().getXlxbList().get(0).getSgdd());
            hb.setText(ZsyjhxxShBean.getInfo().getXlxbList().get(0).getXbmc());
            lc.setText(ZsyjhxxShBean.getInfo().getXlxbList().get(0).getLic());
            xmmc.setText(ZsyjhxxShBean.getInfo().getXmmc());
            sgnr.setText(ZsyjhxxShBean.getInfo().getNrmc());
            sgjx.setText(ZsyjhxxShBean.getInfo().getJxmc());

            if (ZsyjhxxShBean.getInfo().getLb().equals("C")) {
                blfh_layout.setVisibility(View.GONE);
            } else {
                blfh_layout.setVisibility(View.VISIBLE);
                blfh.setText(ZsyjhxxShBean.getInfo().getFhcsmc());
            }

            sgdw.setText(ZsyjhxxShBean.getInfo().getSgdwmc()); //施工单位名称
            sgdwfzr.setText(ZsyjhxxShBean.getInfo().getSgdwfzr());
            jldw.setText(ZsyjhxxShBean.getInfo().getJldw());
            jldwfzr.setText(ZsyjhxxShBean.getInfo().getJldwfzr());
            jsdw.setText(ZsyjhxxShBean.getInfo().getJsdwmc()); //建设单位名称
            cwzd.setText(ZsyjhxxShBean.getInfo().getCwzd());
            sbgldw.setText(ZsyjhxxShBean.getInfo().getSbgldw());
            qtdw.setText(ZsyjhxxShBean.getInfo().getQtdw());
            shcs.setText(ZsyjhxxShBean.getInfo().getShcsmc()); //审核处室名称
            xmzgbm.setText(ZsyjhxxShBean.getInfo().getSpcsmc()); //审批处室名称
            currentSgqd.setText(ZsyjhxxShBean.getInfo().getSection()); //当前施工区段
        }
    }

    @Override
    protected void InitListen() {
        tv_cancel.setOnClickListener(this);
        leftTextView.setOnClickListener(this);
        tv_chakan.setOnClickListener(this);
        tv_shliucheng.setOnClickListener(this);
        tv_hz.setOnClickListener(this);
//        tv_dhz.setOnClickListener(this);
        tv_th.setOnClickListener(this);
        tv_qhqd.setOnClickListener(this);
        tv_szlc.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);
        dialogConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.leftTextView:
                finish();
                break;
            case R.id.tv_cancel:
                finish();
                break;
            //查看历史
            case R.id.tv_chakan:
                JhshHistoryActivity.ZsyjhxxShBean = ZsyjhxxShBean;
                intent = new Intent(this, JhshHistoryActivity.class);
                startActivity(intent);
                break;
            //审核流程
            case R.id.tv_shliucheng:
                CheckInfoActivity.ZsyjhxxShBean = ZsyjhxxShBean;
                intent = new Intent(this, CheckInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_hz:
                //汇总
                mCenterDialog = new CenterDialog(this, new CenterDialog.CenterClick() {
                    @Override
                    public void confirmListener() {
                        mSgbhzPost = new SgbhzPost();
                        mSgbhzPost.setJdjhbBh(ZsyjhxxShBean.getInfo().getBh());
                        mSgbhzPost.setOpeartionType("2");
                        mSgbhzPost.setOpeartionName("汇总");
                        mSgbhzPost.setOpeartionName(MyApplication.getmLoginUser().getTrueName());
                        mSgbhzPost.setOpeartionIp(DeviceUuidFactory.getDeviceId(JhshSgbshActivity.this));
                        mSgbhzPost.setDeleteFlag("N");
                        mSgbhzPost.setCjrId(MyApplication.getmLoginUser().getUserDisplayName());
                        mSgbhzPost.setXgrId(MyApplication.getmLoginUser().getUserDisplayName());
                        MyApplication.ShowWaitDialog(JhshSgbshActivity.this);
                        NetWorkApi.sgbhz(mSgbhzPost, new Callback<SuccessBean>() {
                                    @Override
                                    public void onResponse(Call<SuccessBean> call, Response<SuccessBean> response) {
                                        try {
                                            SuccessBean Bean = response.body();
                                            if (Bean.getMsg().equals("success")) {
                                                MyToast.showToast("汇总成功");
                                                RefreshManager.Sgyjh.RefreshSpywc();
                                                RefreshManager.Sgyjh.RefreshShyjh();
                                                JhshSgbshActivity.this.finish();
                                            }
                                        } catch (Exception e) {
                                            MyToast.showFail();
                                        }
                                        MyApplication.HideWaitDialog();
                                        mCenterDialog.dismiss();
                                    }

                                    @Override
                                    public void onFailure(Call<SuccessBean> call, Throwable t) {
                                        MyToast.showFail();
                                    }
                                }

                        );
                    }

                    @Override
                    public void cancelListener() {
                        mCenterDialog.dismiss();
                    }
                });
                mCenterDialog.setMessage("您确定要汇总该计划吗?");
                mCenterDialog.show();
                break;
            case R.id.tv_th:
                //退回
                mThDialog = new ThDialog(this, ThDialog.SGBSPTH, ZsyjhxxShBean, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyToast.showToast("退回成功");
                        RefreshManager.Sgyjh.RefreshShyjh();
                        RefreshManager.Sgyjh.RefreshSpywc();
                        JhshSgbshActivity.this.finish();
                        mThDialog.dismiss();
                    }
                });
                mThDialog.show();
                break;
            case R.id.tv_qhqd:
                //切换区段
                popupView();
                for (int i = 0; i < mChangeList.size(); i++) {
                    mChangeList.get(i).setSelected(false);
                }
                popListChanged();
                break;
            case R.id.tv_szlc: //设置流程
                YjhFlowSetActivity.ZsyjhxxShBean = ZsyjhxxShBean;
                intent = new Intent(this, YjhFlowSetActivity.class);
                intent.putExtra("flag", "sgb");
                startActivity(intent);
                break;
            case R.id.btn_dialog_cancel: //Dialog取消按钮
                customDialog.dismiss();
                break;
            case R.id.btn_dialog_confirm: //Dialog确定按钮
                postQhqdData();
                break;
            default:
                break;
        }
    }

    //Post提交切换区段的数据
    private void postQhqdData() {
        MySgbOpeartion record = new MySgbOpeartion();
        if (selectQdName.getText().toString().length() > 0) {
            String[] qdName = selectQdName.getText().toString().split(":");
            record.setSelectSection(qdName[1]); //选中的施工区段
        }
        record.setJdjhbBh(ZsyjhxxShBean.getInfo().getBh()); //月计划号
        record.setOpeartionType("5"); //施工办操作类型
        record.setOpeartionName("切换区段"); //施工办操作名称
        record.setOpeartionWorkername(MyApplication.getmLoginUser().getTrueName()); //施工办操作真实姓名
        record.setOpeartionIp(DeviceUuidFactory.getDeviceId(JhshSgbshActivity.this)); //施工办操作IP
        record.setDeleteFlag("N"); //删除标记
        record.setCjrId(MyApplication.getmLoginUser().getUserDisplayName()); //创建人ID
        record.setXgrId(MyApplication.getmLoginUser().getUserDisplayName()); //修改人ID
        MyApplication.ShowWaitDialog(this);
        NetWorkApi.postQhqdData(record, new Callback<SuccessBean>() {
                    @Override
                    public void onResponse(Call<SuccessBean> call, Response<SuccessBean> response) {
                        try {
                            SuccessBean mSuccessBean = response.body();

                            if (mSuccessBean.getMsg().equals("success")) {
                                Toast.makeText(JhshSgbshActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
                                JhshSgbshActivity.this.finish();
                            } else {
                                Toast.makeText(JhshSgbshActivity.this, "设置失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void onFailure(Call<SuccessBean> call, Throwable t) {
                        MyToast.showFail();
                    }
                }
        );
    }

    //PopupWindow数据列表展示
    private void popListChanged() {
        mSelectAdapter = new SelectAdapter();
        //默认显示所有数据，将获取的集合添加到变更集合中
        popListView.setAdapter(mSelectAdapter);
        //ListView的每一项Item的点击事件
        popListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressWarnings("RedundantCast")
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < mChangeList.size(); i++) {
                    mChangeList.get(i).setSelected(false);
                }
                ((SgqdBean.SgqdListBean) (popListView.getAdapter().getItem(position))).setSelected(true);
                mSelectAdapter.notifyDataSetInvalidated();
                selectQdName.setText("选中区段名称为:" + mChangeList.get(position).getAreaName()); //设置选择数据到顶部展示文本上面
            }
        });

        //Edittext的输入框实时列表更改
        popEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) { //输入完成后监听变化,这部分代码后期优化
                mChangeList.clear();
                if (s.length() == 0) {
                    mChangeList.addAll(sgqdBean.getSgqdList());
                    mSelectAdapter.notifyDataSetChanged();
                } else if (s.length() > 0) {
                    mChangeList.addAll(PopUtils.getSearchList(sgqdBean.getSgqdList(), popEdit.getText().toString()));
                    if (PopUtils.getSearchList(sgqdBean.getSgqdList(), popEdit.getText().toString()).size() != 0) {
                        PopUtils.getSearchList(sgqdBean.getSgqdList(), popEdit.getText().toString()).clear();
                    }
                }
                mSelectAdapter.notifyDataSetChanged();
            }
        });

        //PopupWindow底部的总的确定按钮的点击事件
        popConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.show();
            }
        });
    }

    //弹出PopupWindow的窗口
    private void popupView() {
        inflater = LayoutInflater.from(this); //获取一个填充器
        view = inflater.inflate(R.layout.popup_window_qhqdlist, null); //填充自定义的布局
        setArguments(); //设置参数
        popListView = (SHListView) view.findViewById(R.id.select_list);
        popConfirm = (TextView) view.findViewById(R.id.pop_confirm);
        popEdit = (EditText) view.findViewById(R.id.pop_edit);
        selectQdName = (TextView) view.findViewById(R.id.pop_display_text);
    }

    //设置PopupWindow的参数
    public void setArguments() {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        popupWindow = new PopupWindow(view, 2 * width / 3, ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(false);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.8f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });
        //这里传入的是当前所在页面的布局
        popupWindow.showAtLocation(inflater.inflate(R.layout.activity_jhsh_sgbsh, null), Gravity.RIGHT, 0, 0);
    }

    //创建ListView的适配器
    private class SelectAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mChangeList.size();
        }

        @Override
        public Object getItem(int position) {
            return mChangeList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(JhshSgbshActivity.this).inflate(R.layout.item_popwd_select, null);
                holder = new ViewHolder();
                holder.textView = (TextView) convertView.findViewById(R.id.select_text);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.textView.setText(mChangeList.get(position).getAreaName());
            if (mChangeList.get(position).isSelected()) {
                holder.textView.setBackgroundColor(Color.parseColor("#f47979"));
            } else {
                holder.textView.setBackgroundColor(Color.TRANSPARENT);
            }
            return convertView;
        }

        class ViewHolder {
            TextView textView;
        }

    }

    //请求施工区段数据列表接口
    private void requestSgqdList() {
        MyApplication.ShowWaitDialog(this);
        NetWorkApi.getSgqdListData(new Callback<SgqdBean>() {
                                       @Override
                                       public void onResponse(Call<SgqdBean> call, Response<SgqdBean> response) {
                                           try {
                                               sgqdBean = response.body();

                                               if (sgqdBean.getMsg().equals("success")) {
                                                   if (sgqdBean.getSgqdList().size() != 0) {
                                                       mChangeList.addAll(sgqdBean.getSgqdList()); //有数据时将数据加入集合中
                                                   } else {
                                                       Toast.makeText(JhshSgbshActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                                                   }
                                               } else {
                                                   MyToast.showNullObjectError(JhshSgbshActivity.this);
                                               }
                                           } catch (Exception e) {
                                               MyToast.showFail();
                                           }
                                           MyApplication.HideWaitDialog();
                                       }

                                       @Override
                                       public void onFailure(Call<SgqdBean> call, Throwable t) {
                                           MyToast.showFail();
                                       }
                                   }
        );
    }

}
